package common

import (
	"bytes"
	"encoding/json"
	"github.com/3th1nk/cidr"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
	"strconv"
)

func HttpPostJson(jsonStr []byte, url string) (body []byte, statuscode int, header http.Header, err error) {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("access-token", "ZWBOIkde-FQEZv9m_kad47-z7nG19l7g")
	client := &http.Client{}
	resp, err := client.Do(req)
	logrus.Info("Do callback , resp=", resp, ",error=", err)
	if err != nil {
		return body, statuscode, header, err
	}
	defer resp.Body.Close()

	statuscode = resp.StatusCode
	header = resp.Header
	body, _ = ioutil.ReadAll(resp.Body)
	return
}

func ImageURLTest(jsonStr []byte, url string) (body []byte, statuscode int, header http.Header, err error) {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{Timeout: 2}
	resp, err := client.Do(req)
	logrus.Error("Do image url test , resp=", resp, ",error=", err)
	if err != nil {
		return body, statuscode, header, err
	}
	defer resp.Body.Close()

	statuscode = resp.StatusCode
	header = resp.Header
	body, _ = ioutil.ReadAll(resp.Body)
	return
}

func GetGatewayFromCIDR(cidrString string) (gateway string) {
	c, _ := cidr.ParseCIDR(cidrString)
	index := 0
	if err := c.ForEachIP(func(ip string) error {
		if index == 1 {
			gateway = ip
		}
		index++
		return nil
	}); err != nil {
	}
	return
}

// Strval 获取变量的字符串值
// 浮点型 3.0将会转换成字符串3, "3"
// 非数值或字符类型的变量将会被转换成JSON格式字符串
func Strval(value interface{}) string {
	var key string
	if value == nil {
		return key
	}

	switch value.(type) {
	case float64:
		ft := value.(float64)
		key = strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		key = strconv.Itoa(it)
	case uint:
		it := value.(uint)
		key = strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		key = strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		key = strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		key = strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		key = strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		key = strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		key = strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		key = strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		key = strconv.FormatUint(it, 10)
	case string:
		key = value.(string)
	case []byte:
		key = string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		key = string(newValue)
	}

	return key
}
